<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/vue.js"></script>
</head>
<body>
    <div id="root">
        <h2>学生列表</h2>
        <input type="text" v-model="searchName">
        <button @click="sort = 'desc'">年龄倒序</button>
        <button @click="sort = 'asc'">正序</button>
        <button @click="sort = 'normal'">正常</button>
        <ul>
            <li v-for="item of filterStudents" :key="item.id">{{item.name}} --- {{item.age}}</li>
        </ul>
    </div>

    <script>
        new Vue({
            el: '#root',
            data: {
                sort: 'normal',
                searchName: '',
                students: [
                    {id: '001', name: '马冬梅', age: 25},
                    {id: '002', name: '马老二', age: 30},
                    {id: '003', name: '周杰伦', age: 27},
                    {id: '004', name: '林俊杰', age: 28}
                ],
                // filterStudents: []
            },
            computed: {
                filterStudents() {
                    const newArr =  this.students.filter(item => {
                        return item.name.indexOf(this.searchName) > -1;
                    })
                    if (this.sort != 'normal') {
                        newArr.sort((a, b) => {
                            return this.sort == 'asc' ? a.age - b.age : b.age - a.age;
                        })
                    }
                    return newArr
                }
            }
            // watch: {
            //     searchName: {
            //         immediate: true,
            //         handler(newValue) {
            //         // console.log('chongxinsousuole')
            //         this.filterStudents = this.students.filter(item => {
            //             return item.name.indexOf(newValue) > -1;
            //         })
            //     }
            //     }
            // }
        })
    </script>
</body>
</html>